package com.example.scrawldemo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.example.scrawldemo.API.API;
import com.example.scrawldemo.API.Okhttp;
import com.example.scrawldemo.base.BaseApplication;
import com.example.scrawldemo.bean.Code;
import com.example.scrawldemo.bean.RES;
import com.example.scrawldemo.bean.Token;
import com.example.scrawldemo.config.AnnotationConfig;
import com.example.scrawldemo.util.BitmapUtil;
import com.example.scrawldemo.util.JSONUtils;
import com.example.scrawldemo.util.MyOkGoHelper;
import com.example.scrawldemo.widget.ScrawlBoardView;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.leefeng.promptlibrary.PromptButton;
import me.leefeng.promptlibrary.PromptButtonListener;
import me.leefeng.promptlibrary.PromptDialog;

public class ScrawlActivity extends AppCompatActivity {


    @BindView(R.id.board_view)
    ScrawlBoardView boardView;
    @BindView(R.id.scraw_group)
    RelativeLayout scrawGroup;
    @BindView(R.id.yellow_radio)
    RadioButton yellowRadio;
    @BindView(R.id.green_radio)
    RadioButton greenRadio;
    @BindView(R.id.orange_radio)
    RadioButton orangeRadio;
    @BindView(R.id.red_radio)
    RadioButton redRadio;
    @BindView(R.id.blue_radio)
    RadioButton blueRadio;
    @BindView(R.id.purple_radio)
    RadioButton purpleRadio;
    @BindView(R.id.color_group)
    RadioGroup colorGroup;
    @BindView(R.id.layline)
    LinearLayout layline;
    @BindView(R.id.pen)
    ImageView pen;
    @BindView(R.id.rubber)
    ImageView rubber;
    @BindView(R.id.b_w)
    ImageView b_w;
    @BindView(R.id.cut)
    ImageView cut;
    @BindView(R.id.img_back)
    RelativeLayout imgBack;
    @BindView(R.id.layout_selects)
    RelativeLayout layoutSelects;
    @BindView(R.id.title_two)
    LinearLayout title_two;
    @BindView(R.id.img_cancel)
    RelativeLayout imgCancel;
    @BindView(R.id.layout_save)
    RelativeLayout layoutSave;

    String url;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
          url = getIntent().getStringExtra("url");
        boardView.isCan(false);
        if (url.startsWith("http")) {
            Glide.with(this).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(final Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                    if (bitmap==null) {
                        Toast.makeText(ScrawlActivity.this, "网络错误，请检测网络", Toast.LENGTH_SHORT).show();
                    } else {
                        boardView.post(new Runnable() {
                            @Override
                            public void run() {
                                final Bitmap resizeBitmap = BitmapUtil.resizeBitmap(bitmap, boardView);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        boardView.setBackgroud(resizeBitmap);
                                    }
                                });
                            }
                        });

                    }


                }
            }); //方法中设置asBitmap可以设置回调类型

        } else {
            final Bitmap bitmap = BitmapFactory.decodeFile(url);
            boardView.post(new Runnable() {
                @Override
                public void run() {
                    final Bitmap resizeBitmap = BitmapUtil.resizeBitmap(bitmap, boardView);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            boardView.setBackgroud(resizeBitmap);
                        }
                    });
                }
            });
        }




        colorGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.red_radio:
                        boardView.setPaintType(AnnotationConfig.PaintType.Paint_Red);
                        break;
                    case R.id.orange_radio:
                        boardView.setPaintType(AnnotationConfig.PaintType.Paint_Orange);
                        break;
                    case R.id.yellow_radio:
                        boardView.setPaintType(AnnotationConfig.PaintType.Paint_Yellow);
                        break;
                    case R.id.green_radio:
                        boardView.setPaintType(AnnotationConfig.PaintType.Paint_Green);
                        break;
                    case R.id.blue_radio:
                        boardView.setPaintType(AnnotationConfig.PaintType.Paint_Blue);
                        break;
                    case R.id.purple_radio:
                        boardView.setPaintType(AnnotationConfig.PaintType.Paint_Purple);
                        break;

                    default:
                        break;
                }
            }
        });
    }

    Bitmap bitmap  ;
    String imgName ,bitmapname;
    PromptDialog      promptDialogsave;
    PromptDialog    promptDialog;
    @OnClick({R.id.img_back,R.id.pen, R.id.layout_selects, R.id.rubber, R.id.b_w, R.id.cut, R.id.img_cancel, R.id.layout_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;

            case R.id.pen:
                boardView.isCan(true);
                int visibility = layline.getVisibility();
                if (visibility == 0) {
                    layline.setVisibility(View.GONE);
                } else {
                    layline.setVisibility(View.VISIBLE);
                }
                pen.setImageResource(R.drawable.pen_blue);
                rubber.setImageResource(R.drawable.rubber_whites);
                b_w.setImageResource(R.drawable.bw_white);
                cut.setImageResource(R.drawable.cut_white);

                break;
            case R.id.rubber:
                boardView.isCan(true);
                layline.setVisibility(View.GONE);
                boardView.setPaintType(AnnotationConfig.PaintType.Paint_Eraser);
                pen.setImageResource(R.drawable.pen_white);
                rubber.setImageResource(R.drawable.rubber_blues);
                b_w.setImageResource(R.drawable.bw_white);
                cut.setImageResource(R.drawable.cut_white);
                break;
            case R.id.b_w:
                boardView.isCan(false);
                pen.setImageResource(R.drawable.pen_white);
                rubber.setImageResource(R.drawable.rubber_whites);
                b_w.setImageResource(R.drawable.bw_blue);
                cut.setImageResource(R.drawable.cut_white);
                layline.setVisibility(View.GONE);
                Toast.makeText(this, "黑白混色！", Toast.LENGTH_SHORT).show();
//                boardView.cancelPath();
                break;
            case R.id.cut:
                promptDialog = new PromptDialog(this);
                promptDialog.showLoading("正在载入");
                boardView.isCan(false);
                layline.setVisibility(View.GONE);
                pen.setImageResource(R.drawable.pen_white);
                rubber.setImageResource(R.drawable.rubber_whites);
                b_w.setImageResource(R.drawable.bw_white);
                cut.setImageResource(R.drawable.cut_blue);
                Toast.makeText(this, "截图！", Toast.LENGTH_SHORT).show();
                  bitmap = boardView.getSrawBoardBitmap();
                  imgName=System.currentTimeMillis()+".jpg";

                try {
                    String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/MyImg2";
                    File imgDir = new File(filePath);
                    if (!imgDir.exists()) {
                        imgDir.mkdirs();
                    }
                    imgName = filePath + "/" + imgName;
                    FileOutputStream outputStream = new FileOutputStream(imgName);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                    if (promptDialog!=null) {
                        promptDialog.dismiss();
                    }
                    this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + imgName)));
                } catch (Exception e) {
                    e.printStackTrace();
                }


                cropPicture(ScrawlActivity.this,imgName);
                break;

            case R.id.img_cancel:
                boardView.isCan(false);
                layline.setVisibility(View.GONE);
                title_two.setVisibility(View.GONE);
                imgCancel.setVisibility(View.GONE);
                layoutSave.setVisibility(View.GONE);
                imgBack.setVisibility(View.VISIBLE);
                layoutSelects.setVisibility(View.VISIBLE);
                break;
//
//
            case R.id.layout_save:

                boardView.isCan(false);
//                promptDialog = new PromptDialog(this);
//                promptDialog.showLoading("正在保存");



                  bitmap = boardView.getSrawBoardBitmap();
                Log.e("888", "xx"+bitmap);
                layline.setVisibility(View.GONE);
                title_two.setVisibility(View.GONE);
                imgBack.setVisibility(View.VISIBLE);
                layoutSelects.setVisibility(View.VISIBLE);
                imgCancel.setVisibility(View.GONE);
                layoutSave.setVisibility(View.GONE);
                //该处的bitmap是涂鸦好的图片。
                //该例子中是把涂鸦好的图片保存到本地
                  bitmapname=System.currentTimeMillis()+".jpg";
                saveBitmap(bitmap,bitmapname);
                boardView.setPaintType(AnnotationConfig.PaintType.Paint_Yellow);
//                try {
//                    String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/MyImg3";
//                    File imgDir = new File(filePath);
//                    if (!imgDir.exists()) {
//                        imgDir.mkdirs();
//                    }
//                    imgName = filePath + "/" + bitmapname;
//                    FileOutputStream out = new FileOutputStream(imgName);
////                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
////                    promptDialog.showSuccess("保存成功！");
////                    // 发送广播，通知刷新图库的显示
////                    this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + imgName)));
//                    if(bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out))
//                    {
//                        out.flush();
//                        out.close();
//// 插入图库
//                        MediaStore.Images.Media.insertImage(this.getContentResolver(), imgDir.getAbsolutePath(), bitmapname, null);
//                        promptDialog.showSuccess("保存成功！");
//                    }
//                } catch (Exception e) {
//                    promptDialog.showError("保存失败！");
//                    e.printStackTrace();
//                }


                break;


            case R.id.layout_selects:
                /********************底部AlertSheet*************/
                  promptDialog = new PromptDialog(this);
                PromptButton cancle = new PromptButton("取消", null);
                promptDialog.showAlertSheet("", true, cancle, new PromptButton("收藏", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                if (url.startsWith("http")) {
                                    Glide.with(ScrawlActivity.this).load(url).asBitmap().toBytes().into(new SimpleTarget<byte[]>() {
                                        @Override
                                        public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
                                            try {
                                                //收藏第一步保存到本地
                                                promptDialogsave = new PromptDialog(ScrawlActivity.this);
                                                promptDialogsave.showLoading("正在收藏");
                                                savaBitmap_temporary("" + System.currentTimeMillis()+".jpg", bytes);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                dissmiss();
                                            }
                                        }
                                    });

                                } else {
                                    promptDialogsave = new PromptDialog(ScrawlActivity.this);
                                    promptDialogsave.showLoading("正在收藏");
                                    //保存本地图片
                                    gettoken(url);
                                }

                            }
                        }),
                        new PromptButton("保存到相册", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                if (url.startsWith("http")) {
                                    Glide.with(ScrawlActivity.this).load(url).asBitmap().toBytes().into(new SimpleTarget<byte[]>() {
                                        @Override
                                        public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
                                            try {
                                                savaBitmap("" + System.currentTimeMillis()+".jpg", bytes);
                                            } catch (Exception e) {
                                                e.printStackTrace();

                                            }
                                        }
                                    });

                                } else {
                                    //保存本地图片
                                    final Bitmap bitmap = BitmapFactory.decodeFile(url);
                                    saveBitmap(bitmap,""+System.currentTimeMillis()+".jpg");

                                }



                            }
                        }), new PromptButton("编辑", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                boardView.setPaintType(AnnotationConfig.PaintType.Paint_Yellow);
                                yellowRadio.setChecked(true);
                                boardView.isCan(true);
                                layline.setVisibility(View.VISIBLE);
                                title_two.setVisibility(View.VISIBLE);
                                imgBack.setVisibility(View.GONE);
                                layoutSelects.setVisibility(View.GONE);
                                imgCancel.setVisibility(View.VISIBLE);
                                layoutSave.setVisibility(View.VISIBLE);

                            }
                        })
                );
                break;


            default:
                break;
        }
    }

    /**
     * 网络图片保存到相册
     * @param imgName
     * @param bytes
     */
    public void savaBitmap(String imgName, byte[] bytes) {

        promptDialog = new PromptDialog(this);
        promptDialog.showLoading("正在保存");
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String filePath = null;
            FileOutputStream fos = null;
            try {
                filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/MyImg";
                File imgDir = new File(filePath);
                if (!imgDir.exists()) {
                    imgDir.mkdirs();
                }
                imgName = filePath + "/" + imgName;
                fos = new FileOutputStream(imgName);
                fos.write(bytes);
                promptDialog.showSuccess("保存成功！");
                this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + imgName)));

            } catch (IOException e) {
                e.printStackTrace();
                promptDialog.showError("保存失败！");
            } finally {
                try {
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Toast.makeText(this, "请检查SD卡是否可用", Toast.LENGTH_SHORT).show();
        }
    }



    /**
     * 获得token
     * @param filePath
     */
    public void  gettoken(final String filePath){
    API.GetValue(ScrawlActivity.this,new MyOkGoHelper.Objectcallback() {
        @Override
        public void onsuccess(String st) {
            Log.e("888", "xx"+st);
            Token token = JSONUtils.parseJSON(st, Token.class);

            ShangChuan(filePath,token.getData().getToken(),token.getData().getBucketUrl());
        }

        @Override
        public void onFalia(int code, String errst) {
            dissmiss();
        }
    });
}

    public void  ShangChuan(final String imgUrl ,String token,final String bucketUrl){

       String    key=  imgUrl.substring(imgUrl.lastIndexOf("/")+1);
        Log.e("888", "imgUrl:"+imgUrl);
        Log.e("888", "key:"+key);
        Log.e("888", "token:"+token);
        BaseApplication.getUploadManager().put(imgUrl, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if(info.isOK()) {
                            Log.e("888", "Upload Success");
                            RES res1 = JSONUtils.parseJSON(res.toString(), RES.class);
                            String url = bucketUrl+"/"+res1.getKey();
                            Submit_collection(url,key,imgUrl);
                        } else {
                            dissmiss();
                            Log.e("888", "Upload Fail");
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
                        Log.e("888", key + ",\r\n " + info + ",\r\n " + res);
                    }
                }, null);

    }

    public  void Submit_collection(String url, String key, String  imgUrl){
        API.PostData( ScrawlActivity.this,url, key, new File(imgUrl).length() + "", new MyOkGoHelper.Objectcallback() {
            @Override
            public void onsuccess(String st) {
                Log.e("888", "xx"+st);
                Code code = JSONUtils.parseJSON(st, Code.class);
                if (code.getCode()==0) {
                    promptDialogsave.showSuccess("收藏成功");
                    promptDialogsave.dismiss();
                } else {
                    dissmiss();
                }



            }

            @Override
            public void onFalia(int code, String errst) {
                Log.e("888", "errst"+errst);
                dissmiss();
            }
        });
    }
    public void  dissmiss(){
        if (promptDialogsave!=null) {
            promptDialogsave.showError("收藏失败");
//            promptDialogsave.dismiss();

        }
    }

    /**
     * 保存本地文件到相册
     */
    String fileName ;
    public void saveBitmap(Bitmap bitmap, String bitName){

//        File file ;
        promptDialog = new PromptDialog(this);
        promptDialog.showLoading("正在保存");


        FileOutputStream out;
        try{
//            fileName =Environment.getExternalStorageDirectory().getCanonicalPath() + "/MyImg/"+bitName ;
//            file = new File(fileName);

          String  filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/MyImg";
            File imgDir = new File(filePath);
            if (!imgDir.exists()) {
                imgDir.mkdirs();
            }
            imgName = filePath + "/" + bitName;
            out = new FileOutputStream(imgName);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if(bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out))
            {
                out.flush();
                out.close();
// 插入图库
//                MediaStore.Images.Media.insertImage(this.getContentResolver(), imgDir.getAbsolutePath(), bitName, null);
                promptDialog.showSuccess("保存成功！");
                this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + imgName)));
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            promptDialog.showError("保存失败！");
        }

        // 发送广播，通知刷新图库的显示


    }

    /**
     * 网络图片保存到临时本地
     * @param imgName
     * @param bytes
     */
    public void savaBitmap_temporary(String imgName, byte[] bytes) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String filePath = null;
            FileOutputStream fos = null;
            try {
                filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/MyImg";
                File imgDir = new File(filePath);
                if (!imgDir.exists()) {
                    imgDir.mkdirs();
                }
                imgName = filePath + "/" + imgName;
                fos = new FileOutputStream(imgName);
                fos.write(bytes);
//                Toast.makeText(this, "图片已保存到" + filePath, Toast.LENGTH_SHORT).show();
                gettoken(imgName);
            } catch (IOException e) {
                e.printStackTrace();
                dissmiss();
            } finally {
                try {
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            dissmiss();
            Toast.makeText(this, "请检查SD卡是否可用", Toast.LENGTH_SHORT).show();
        }
    }
    //剪切图片
    private static final int REQUEST_CODE_CROP_PICTURE = 11113;

    //截图图片名
    private String crop_image;
    private String DATE = "";

    private int widthScale = 16;//长宽 比例
    private int heightScale = 9;
    private boolean resetCropSize = false;
    /**
     * 调用系统剪裁功能
     */
//    private static final String FILE_CONTENT_FILE_PROVIDER = "com.accp.juli.fileprovider";
    public void cropPicture(Activity activity, String path) {
//        if (!resetCropSize) {
//            widthScale = 16;
//            heightScale = 9;
//        }
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri;
        Uri outputUri;
        crop_image = createImagePath("crop_" + DATE);

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            imageUri = FileProvider.getUriForFile(activity, BaseApplication.getInstance().getPackageName() + ".provider", file);
            outputUri = Uri.fromFile(new File(crop_image));
            //outputUri不需要ContentUri,否则失败
            //outputUri = FileProvider.getUriForFile(activity, "com.solux.furniture.fileprovider", new File(crop_image));
        } else {
            imageUri = Uri.fromFile(file);
            outputUri = Uri.fromFile(new File(crop_image));
        }
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        //设置宽高比例
//        intent.putExtra("aspectX", widthScale);
//        intent.putExtra("aspectY", heightScale);
        //设置裁剪图片宽高
//        intent.putExtra("outputX", 526);
//        intent.putExtra("outputY", 246);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        activity.startActivityForResult(intent, REQUEST_CODE_CROP_PICTURE);
        resetCropSize = false;
    }
    /**
     * 创建图片的存储路径
     */
    private static String createImagePath(String imageName) {
        String dir = Environment.getExternalStorageDirectory() + "/Craw/photo";
        File destDir = new File(dir);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File file = null;
        if (!TextUtils.isEmpty(imageName)) {
            file = new File(dir, imageName + ".jpg");
        }
        return file.getAbsolutePath();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1)
            switch (requestCode) {
                case REQUEST_CODE_CROP_PICTURE:
                    if (!TextUtils.isEmpty(crop_image)) {
                        File file = new File(crop_image);
                        if (file.isFile())
                            Log.e("TAG", "剪切路径==" + crop_image);
                        final Bitmap bitmap = BitmapFactory.decodeFile(crop_image);
                        boardView.post(new Runnable() {
                            @Override
                            public void run() {
                                final Bitmap resizeBitmap = BitmapUtil.resizeBitmap(bitmap, boardView);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        boardView.setBackgroud(resizeBitmap);
                                    }
                                });
                            }
                        });


                    }
                    break;
            }
        else
            Log.e("TAG", "onActivityResult: resultCode==" + resultCode);
    }
}
